import { updateData } from '../reducer/index';

let hospitalList = window.hospitalLists;
let deviceIDList = [];
let hospitalNameList = Object.keys(hospitalList);
hospitalNameList.forEach(key => {
  Array.prototype.push.apply(deviceIDList, hospitalList[key]);
});

updateData({
  hospitalList,
  deviceIDList,
  hospitalNameList
});

export let initData = async () => {

  // 保存管理员token
  let tokenRes = await window.getToken();
  if (tokenRes?.result?.msg !== "操作成功。") {
    let msg = tokenRes?.result?.msg;
    alert(msg ? msg : '数据获取失败');
    console.log(tokenRes);
    return;
  }
  let accessToken = tokenRes.result.data.accessToken;
  updateData({
    accessToken
  });

  await firstQueryDeviceInfo(deviceIDList);
}

export async function firstQueryDeviceInfo(deviceIDList) {
  let {
    accessToken
  } = window.$getState();
  const deviceIds = deviceIDList.slice(0, 8).join(',');
  let bindDeviceListRes = await window.bindDeviceList({
    deviceIds,
    token: accessToken,
  });
  if (bindDeviceListRes?.result?.msg !== "操作成功。") {
    let msg = bindDeviceListRes?.result?.msg;
    alert(msg ? msg : '数据获取失败');
    console.log(bindDeviceListRes);
    return;
  }
  updateData({
    deviceList: [bindDeviceListRes.result.data]
  });
}